package com.chuangyang.fixboxlib.widgets;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.AbsListView;

import com.chuangyang.fixboxlib.widgets.swipelistview.SwipeListView;

/**
 * Created by vanshu on 15/4/24 15:17.
 */
public class PullDownRefreshSwipeListView extends SwipeListView  implements AbsListView.OnScrollListener{
    private LoadingFooter mLoadingFooter;
    public OnRefreshListener onRefreshListener;

    public PullDownRefreshSwipeListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }


    private void init(Context context) {
        mLoadingFooter = new LoadingFooter(context);
        addFooterView(mLoadingFooter.getView());
        setOnScrollListener(this);
    }

    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (mLoadingFooter.getState() == LoadingFooter.State.Loading
                || mLoadingFooter.getState() == LoadingFooter.State.TheEnd) {
            return;
        }
        if (firstVisibleItem + visibleItemCount >= totalItemCount
                && totalItemCount != 0
                && totalItemCount != getHeaderViewsCount()
                + getFooterViewsCount() && getCount() > 0) {
            onRefreshListener.onRefresh();
        }
    }


    public void setLoading() {
        mLoadingFooter.setState(LoadingFooter.State.Loading);
    }

    public void setLoadingEnd() {
        mLoadingFooter.setState(LoadingFooter.State.TheEnd);
    }

    public void setLoadingIdle() {
        mLoadingFooter.setState(LoadingFooter.State.Idle);
    }

    public void setLoadingIdleDelay(long delayMills) {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mLoadingFooter.setState(LoadingFooter.State.Idle);
            }
        },delayMills);
    }


    public interface OnRefreshListener {
        void onRefresh();
    }

}
